import React, { useEffect, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  Button,
  Collapse,
  DatePicker,
  Form,
  FormInstance,
  Input,
  InputNumber,
  Modal,
  Spin,
  message,
  Switch,
} from "antd";
import { SidebarStaff } from "../../../components/Sidebar";
import { Question } from "../../../utils/constant";
import {
  CreateQuestion,
  DeleteQuestion,
  GetConfig,
  GetQuestions,
  Pairing,
  UpdateConfig,
} from "../../../api";

import "./index.less";
import { CloseOutlined } from "@ant-design/icons";
import { formatTimeString } from "../../../utils/time";
import { DOMAIN } from "../../../utils/constant";

const { Panel } = Collapse;

const formRules = [{ required: true }];

interface QuestionForm {
  questionText: string;
  questionDesc: string;
  criteria: string;
  minMark: number;
  maxMark: number;
  duration: Date[];
}

interface GradeCalculationConfig {
  assignmentId?: number | undefined;
  includeParticipation?: number | undefined; // 0 or 1
  ptcWeight?: number | null | undefined;
  includeOutliers?: number | undefined; // 0 or 1
  includeHighest?: number | undefined; // 0 or 1
  includeLowest?: number | undefined; // 0 or 1
}

const Index: React.FC = ({}) => {
  const params = useParams();
  const moduleId = +params.id!;
  const assignmentId = +params.assignmentId!;
  const [isAddModalOpen, setIsAddModalOpen] = useState<boolean>(false);
  const [isConfigModalOpen, setIsConfigModalOpen] = useState<boolean>(false);
  const navigate = useNavigate();
  const [config, setConfig] = useState<GradeCalculationConfig | null>(null);
  const [updatedConfig, setUpdatedConfig] =
    useState<GradeCalculationConfig | null>({
      includeParticipation: 0,
      assignmentId: assignmentId,
      ptcWeight: 0,
      includeOutliers: 1,
      includeHighest: 1,
      includeLowest: 1,
    });
  const formRef = useRef<FormInstance>(null);

  const [questions, setQuestions] = useState<Question[]>([]);

  const openAddModal = () => {
    setIsAddModalOpen(true);
  };

  const closeAddModal = () => {
    setIsAddModalOpen(false);
  };

  const openConfigModal = () => {
    setIsConfigModalOpen(true);
  };

  const closeConfigModal = () => {
    setIsConfigModalOpen(false);
  };

  const fetchQuestionList = async () => {
    try {
      const res = await GetQuestions({ assignmentId });
      setQuestions(res.data);
    } catch (e) {
      console.error(e);
    }
  };

  const handleCreateQuestion = async (data: QuestionForm) => {
    try {
      const {
        questionDesc,
        questionText,
        maxMark,
        minMark,
        duration,
        criteria,
      } = data;
      const { data: question } = await CreateQuestion({
        assignmentId,
        description: questionDesc,
        questionText,
        criteria,
        maxMark,
        minMark,
        startDate: duration[0].valueOf(),
        endDate: duration[1].valueOf(),
      });
      formRef.current?.resetFields();
      setQuestions((questions) => [...questions, question]);
      closeAddModal();
      message.success("Add Success");
    } catch (e) {
      console.error(e);
    }
  };

  useEffect(() => {
    fetchQuestionList();
  }, []);

  const deleteConfirm = (id: number) => {
    Modal.confirm({
      title: "Are you sure to delete?",
      okText: "Yes",
      cancelText: "Cancel",
      onOk: () => {
        handleDelete(id);
      },
    });
  };

  const handleDelete = async (id: number) => {
    try {
      await DeleteQuestion({ ids: [id] });
      await fetchQuestionList();
    } catch (e) {
      console.error(e);
    }
  };

  const handlePair = () => {
    navigate(`/staff/module/${moduleId}/assignments/${assignmentId}/pair`);
  };

  const handleGetConfig = async () => {
    try {
      const response = await GetConfig(assignmentId); // 调用后端 getConfig 方法
      const responseData = response.data;
      setConfig(responseData);
      setUpdatedConfig(responseData);

      openConfigModal();
    } catch (error) {
      console.error("Error fetching configuration: ", error);
      message.error("Failed to fetch configuration.");
    }
  };

  const handleSave = async () => {
    try {
      const response = await UpdateConfig(updatedConfig);

      if (response.success) {
        message.success("Configuration updated successfully.");
        setConfig(response.data);
        closeConfigModal();
      } else {
        message.error("Failed to update configuration.");
      }
    } catch (error) {
      console.error("Error updating configuration: ", error);
      message.error("Failed to update configuration.");
    }
  };

  return (
    <>
      <SidebarStaff></SidebarStaff>
      <div className="question-list">
        <div className="question-list-header">
          <Button onClick={handlePair} type="primary" className="pair-btn">
            Pair
          </Button>
          <Button
            type="primary"
            onClick={openAddModal}
            className="add-question-btn"
          >
            Add Question
          </Button>
        </div>

        <div className="question-list-content">
          <Collapse className="question-card">
            {questions.map((item, index) => (
              <Panel
                header={`Question ${index + 1}`}
                key={item.id}
                extra={
                  <Button
                    icon={<CloseOutlined />}
                    onClick={(e) => {
                      e.stopPropagation();
                      deleteConfirm(item.id);
                    }}
                  ></Button>
                }
              >
                <p>Question: {item.questionText}</p>
                <p>Criteria: {item.criteria}</p>
                <p>Criteria Description: {item.description}</p>
                <p>Min Mark: {item.minMark}</p>
                <p>Max Mark: {item.maxMark}</p>
                <p>
                  Duration: {formatTimeString(item.startDate)} -{" "}
                  {formatTimeString(item.endDate)}
                </p>
              </Panel>
            ))}
          </Collapse>
        </div>
        <div className="final-grade">
          <Button
            type="primary"
            className="download-grades-btn"
            onClick={() => {
              window.open(
                `http://${DOMAIN}/grade/downloadGrades/${assignmentId}`
              );
            }}
          >
            Download Grades
          </Button>
          <Button
            type="primary"
            className="config-calculation-btn"
            onClick={handleGetConfig}
          >
            Config Calculation
          </Button>
        </div>
      </div>
      <Modal
        title="Add Question"
        open={isAddModalOpen}
        footer={null}
        closable={true}
        onCancel={closeAddModal}
        maskClosable={true}
      >
        <Form ref={formRef} onFinish={handleCreateQuestion}>
          <Form.Item label="QuestionText" name="questionText" rules={formRules}>
            <Input.TextArea></Input.TextArea>
          </Form.Item>
          <Form.Item label="Criteria" name="criteria" rules={formRules}>
            <Input.TextArea></Input.TextArea>
          </Form.Item>
          <Form.Item label="CriteriaDesc" name="questionDesc" rules={formRules}>
            <Input.TextArea></Input.TextArea>
          </Form.Item>
          <Form.Item label="MinMark" name="minMark" rules={formRules}>
            <InputNumber min={0}></InputNumber>
          </Form.Item>
          <Form.Item label="MaxMark" name="maxMark" rules={formRules}>
            <InputNumber min={0}></InputNumber>
          </Form.Item>
          <Form.Item label="Duration" name="duration" rules={formRules}>
            <DatePicker.RangePicker></DatePicker.RangePicker>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="Calculation Configuration"
        open={isConfigModalOpen}
        onCancel={closeConfigModal}
        footer={null}
        closable={true}
        maskClosable={true}
      >
        <Form>
          {config && updatedConfig ? (
            <>
              <Form.Item label="Include Participation Marks">
                <Switch
                  checked={updatedConfig?.includeParticipation === 1}
                  onChange={(checked) =>
                    setUpdatedConfig((prevConfig) => ({
                      ...prevConfig,
                      includeParticipation: checked ? 1 : 0,
                    }))
                  }
                />
              </Form.Item>
              <Form.Item label="Participation Weight">
                <InputNumber
                  min={0}
                  max={1}
                  step={0.01}
                  value={updatedConfig?.ptcWeight}
                  onChange={(value) =>
                    setUpdatedConfig((prevConfig) => ({
                      ...prevConfig,
                      ptcWeight: value,
                    }))
                  }
                />
              </Form.Item>
              <Form.Item label="Include Highest Marks">
                <Switch
                  checked={updatedConfig?.includeHighest === 1}
                  onChange={(checked) =>
                    setUpdatedConfig((prevConfig) => ({
                      ...prevConfig,
                      includeHighest: checked ? 1 : 0,
                    }))
                  }
                />
              </Form.Item>
              <Form.Item label="Include Lowest Marks">
                <Switch
                  checked={updatedConfig?.includeLowest === 1}
                  onChange={(checked) =>
                    setUpdatedConfig((prevConfig) => ({
                      ...prevConfig,
                      includeLowest: checked ? 1 : 0,
                    }))
                  }
                />
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit" onClick={handleSave}>
                  Save
                </Button>
              </Form.Item>
            </>
          ) : (
            <p>No configuration available.</p>
          )}
        </Form>
      </Modal>
    </>
  );
};

export default Index;
